$(function() {
	var userId = $('#userId').val();
	var ifcart = $('#ifcart').val();
	if(ifcart==1){
		var cart_id = $('#cartid').val();
		var data = {userId:userId,ifcart:1,cartId:cart_id};
		//alert(data.cartId);
	}else{
		var goods_id = GetQueryString("goods_id");
		var number = GetQueryString("buynum");
		var cart_id = goods_id+'|'+number;
		var data = {userId:userId};
	}

    var isFCode = false;

    var pf = function(f) {
        return parseFloat(f) || 0;
    };

    var p2f = function(f) {
        return (parseFloat(f) || 0).toFixed(2);
    };

    var isEmpty = function(o) {
        var b = true;
        $.each(o, function(k, v) {
            b = false;
            return false;
        });
        return b;
    };

    //var cod = (function() {
    //    // COD开关
    //    var codSwitch = $('#buy-type-offline').prop('checked');
    //
    //    // COD状态
    //    var codGlobal = false;
    //    var codStores = {};
    //
    //    // 0b1 正在使用货到付款
    //    // 0b2 可以使用预存款和充值卡
    //    var paymentFlag = 2;
    //
    //    var stateChanged = function() {
    //        if (codGlobal) {
    //            var flag1 = false;
    //            var flag2 = false;
    //
    //            $('.store-cod-supported').each(function() {
    //                if (codStores[$(this).data('store_id')]) {
    //                    $(this).hide();
    //                    flag1 = flag1 || true;
    //                } else {
    //                    $(this).show();
    //                    flag2 = flag2 || true;
    //                }
    //            });
    //
    //            paymentFlag = 0;
    //
    //            if (flag1) {
    //                paymentFlag |= 1;
    //            }
    //            if (flag2) {
    //                paymentFlag |= 2;
    //            }
    //        } else {
    //            $('.store-cod-supported').hide();
    //
    //            paymentFlag = 2;
    //        }
    //
    //        switch (paymentFlag) {
    //        case 1:
    //            // 支持货到付款的同时不支持在线支付
    //            $('#offline').show();
    //            $('#deposit').hide();
    //            break;
    //
    //        case 3:
    //            // 支持货到付款的同时支持在线支付
    //            $('#offline').show();
    //            $('#deposit').show();
    //            break;
    //
    //        case 0:
    //            // none
    //        case 2:
    //            // 只支持在线支付
    //        default:
    //            // default
    //            $('#buy-type-offline').prop('checked', false);
    //            $('#buy-type-online').prop('checked', true);
    //
    //            // 关闭COD开关
    //            codSwitch = false;
    //
    //            $('#offline').hide();
    //            $('#deposit').show();
    //            break;
    //        }
    //
    //        // 在线支付默认优先开关控制
    //        if (!codSwitch) {
    //            $('#deposit').show();
    //        }
    //
    //        refleshTotals();
    //    };
    //
    //    var refleshTotals = function() {
    //        if (codSwitch && codGlobal) {
    //            var codTotal = 0;
    //            var onlineTotal = 0;
    //
    //            $('.store_total').each(function() {
    //                var sid = this.id.substring(2);
    //                var st = parseFloat(this.innerHTML) || 0;
    //                if (codStores[sid]) {
    //                    codTotal += st;
    //                } else {
    //                    onlineTotal += st;
    //                }
    //            });
    //
    //            //console.log(codTotal);
    //            //console.log(onlineTotal);
    //            $('#online-total-wrapper').show();
    //            $('#online-total').html(p2f(onlineTotal));
    //        } else {
    //            $('#online-total-wrapper').hide();
    //        }
    //    };
    //
    //    var switchTriggered = function(b) {
    //        codSwitch = b;
    //
    //        stateChanged();
    //    };
    //
    //    var stateUpdateded = function(allow_offpay, allow_offpay_batch) {
    //        codGlobal = allow_offpay == '1';
    //        codStores = allow_offpay_batch || {};
    //
    //        stateChanged();
    //    };
    //
    //    return {
    //        switchTriggered: switchTriggered,
    //        stateUpdateded: stateUpdateded,
    //        refleshTotals: refleshTotals,
    //        z: 0
    //    };
    //})();

	//获取默认地址信息
	$.ajax({
		type:'post',
		url:WapSiteUrl+'/address/addressInfo',
		dataType:'json',
		data:{userId:userId},
		success:function(result) {
			var data = result.datas;
			//alert("address:" + data);
			if (result.error!= null) {
				location.href = WapSiteUrl;
			}
			//alert("address:"+data);
			if (data == null) {//收获地址是否存在
				//如果是发票 就是buys1-invoice-cnt
				var thisPrarent = $(".buys1-address-cnt");
				hideDetail(thisPrarent);
				//填写收获地址
			} else {
				$('#true_name').html(data.trueName);
				$('#address').html(data.areaInfo + ' ' + data.address);
				$('#mob_phone').html(data.mobPhone);

				$('input[name=address_id]').val(data.addressId);
				$('input[name=area_id]').val(data.areaId);
				$('input[name=city_id]').val(data.cityId);
			}
			// 点击使用新地址才显示新地址编辑框
			$('#new-address-button').click(function () {
				$('#new-address-wrapper').show();
			});


		}
	});

	//获取发票抬头下拉列表内容
	$.ajax({
		type:'post',
		url:WapSiteUrl+'/invoice/contentList',
		data:{userId:userId},
		dataType:'json',
		success:function(result){
			//checklogin(result.login);
			var data = result.datas;
			var html = '';
			$.each(data,function(k,v){
				html+='<option value="'+v+'">'+v+'</option>';
			});
			//alert(html);
			$('#inc_content').append(html);
		}
	});

	$.ajax({//获取区域列表
		type:'post',
		url:WapSiteUrl+'/address/areaList',
		dataType:'json',
		success:function(result){
			var data = result.datas;
			var prov_html = '';
			for(var i=0;i<data.length;i++){
				prov_html+='<option value="'+data[i].areaId+'">'+data[i].areaName+'</option>';
			}
			$("select[name=prov]").append(prov_html);
		}
	});

	$("select[name=prov]").change(function(){//选择省市
		var prov_id = $(this).val();
		$.ajax({
			type:'post',
			url:WapSiteUrl+'/address/areaList',
			data:{paId:prov_id},
			dataType:'json',
			success:function(result){
				//checklogin(result.login);
				var data = result.datas;
				var city_html = '<option value="">请选择...</option>';
				for(var i=0;i<data.length;i++){
					city_html+='<option value="'+data[i].areaId+'">'+data[i].areaName+'</option>';
				}
				$("select[name=city]").html(city_html);
				$("select[name=region]").html('<option value="">请选择...</option>');
			}
		});
	});

	$("select[name=city]").change(function(){//选择城市
		var city_id = $(this).val();
		$.ajax({
			type:'post',
			url:WapSiteUrl+'/address/areaList',
			data:{paId:city_id},
			dataType:'json',
			success:function(result){
				//checklogin(result.login);
				var data = result.datas;
				var region_html = '<option value="">请选择...</option>';
				for(var i=0;i<data.length;i++){
					region_html+='<option value="'+data[i].areaId+'">'+data[i].areaName+'</option>';
				}
				$("select[name=region]").html(region_html);
			}
		});
	});

	//获取用户保存过的发票列表
	$.ajax({
		type:'post',
		url:WapSiteUrl+'/invoice/list',
		data:{userId:userId},
		dataType:'json',
		success:function(result){
			//alert("invoice res:"+result);
			var invoice = result.datas;
			if(invoice.length>0){
				var html = '';
				$.each(invoice,function(k,v){
					html+= '<li>'
								+'<label>'
									+'<input type="radio" name="invoice" class="rdo inv-radio" checked="checked" value="'+v.invId+'"/>'
									+'<span class="mr5 rdo-span" id="inv_'+v.invId+'">'+v.invTitle+'&nbsp;&nbsp;'+v.invContent+'</span>'
								+'</label>'
								+'<a class="del-invoice" href="javascript:void(0);" inv_id="'+v.invId+'">[删除]</a>'
							+'</li>';
				});
				//alert("invoice:"+html);
				$('#invoice_add').before(html);

				$('.del-invoice').click(function(){
                    var $this = $(this);
					var inv_id = $(this).attr('inv_id');
					$.ajax({
						type:'post',
						url:WapSiteUrl+'/invoice/delete',
						data:{userId:userId,invId:inv_id},
						success:function(result){
							if(result){
								$this.parent('li').remove();
							}
							return false;
						}
					});
				});
			}
		}
	});
    $(".head-invoice").click(function (){
        $(this).parent().find(".inv-tlt-sle").prop("checked",true);
    });
	//修改收货地址
    $(".buys1-edit-address").click(function(){
		//alert("edit address");
        var self = this;
		//发送ajax请求获取所有可用的地址列表
        $.ajax({
        	url: WapSiteUrl+"/address/list",
        	type:'post',
        	data:{userId:userId},
        	dataType:'json',
        	success:function(result){
        		var data = result.datas;
        		var html = '';
        		for(var i=0;i<data.length;i++){
					var checked = "";
					var isDefault = "";
					if(data[i].isDefault=='1'){
						checked = "checked";
						isDefault = "[默认地址]";
					}
        			html+='<li class="current existent-address">'
			                    +'<label>'
			                        +'<input type="radio" name="address" '+checked+' class="rdo address-radio" value="'+data[i].addressId+'" city_id="'+data[i].cityId+'" area_id="'+data[i].areaId+'" />'
			                        +'<span class="mr5 rdo-span"><span class="true_name_'+data[i].addressId+'">'+data[i].trueName+'</span> <span class="address_id_'+data[i].addressId+'">'+data[i].areaInfo+' '+data[i].address+'</span> <span class="mob_phone_'+data[i].addressId+'">'+data[i].mobPhone+' '+isDefault+'</span></span>'
			                    +'</label>'
			                    +'<a class="del-address" href="javascript:void(0);" address_id="'+data[i].addressId+'">[删除]</a>'
                    		+'</li>';
        		}
				//alert(html);
        		$('li.existent-address').remove();
        		$('#addresslist').before(html);

                // 点击已有地址 隐藏新地址输入框
                $('li.existent-address input').click(function() {
                    $('#new-address-wrapper').hide();
                });

        		$('.del-address').click(function(){
                    var $this = $(this);
        			var address_id = $(this).attr('address_id');
					//alert("sss");
        			$.ajax({
        				type:'post',
        				url:WapSiteUrl+'/address/delete',
        				data:{addressId:address_id,userId:userId},
        				dataType:'json',
        				success:function(result){
        					$this.parent('li').remove();
        				}
        			});
        		});

                $('input[name=address]').click(function() {
                    var city_id = $(this).attr('city_id');
                    var area_id = $(this).attr('area_id');

                    $('input[name=city_id]').val(city_id);
                    $('input[name=area_id]').val(area_id);
                });
        	}
        });
        var thisPrarent = $(this).parents(".buys1-address-cnt");
        hideDetail(thisPrarent);
    });
    $(".buys1-edit-invoice").click(function(){
        var self = this;

        var thisPrarent = $(this).parents(".buys1-invoice-cnt");
        hideDetail(thisPrarent);
    });

	$.sValid.init({//地址验证
        rules:{
        	vtrue_name:"required",
        	vmob_phone:"required",
            vprov:"required",
            vcity:"required",
            vregion:"required",
            vaddress:"required"
        },
        messages:{
        	vtrue_name:"姓名必填！",
        	vmob_phone:"手机号必填！",
            vprov:"省份必填！",
            vcity:"城市必填！",
            vregion:"区县必填！",
            vaddress:"街道必填！"
        },
        callback:function (eId,eMsg,eRules){
            if(eId.length >0){
                var errorHtml = "";
                $.map(eMsg,function (idx,item){
                    errorHtml += "<p>"+idx+"</p>";
                });
                $(".error-tips").html(errorHtml).show();
            }else{
                 $(".error-tips").html("").hide();
            }
        }
    });

    $(".save-address").click(function (){//更换收获地址
        var self = this;
        var selfPr;
        //获取address_id
        var addressRadio = $('.address-radio');
        var address_id;
        for(var i =0;i<addressRadio.length;i++){
            if(addressRadio[i].checked){
                address_id = addressRadio[i].value;
            }
        }

        if(address_id>0){//变更地址
        	var area_id = $("input[name=area_id]").val();
        	var city_id = $("input[name=city_id]").val();
        	//var freight_hash = $("input[name=freight_hash]").val();
			$("input[name=address_id]").val(address_id);
			$('#address').html($('.address_id_'+address_id).html());
			$('#true_name').html($('.true_name_'+address_id).html());
			$('#mob_phone').html($('.mob_phone_'+address_id).html());

			//cod.stateUpdateded(result.datas.allow_offpay, result.datas.allow_offpay_batch);

			//$('input[name=allow_offpay]').val(result.datas.allow_offpay);
			//$('input[name=offpay_hash]').val(result.datas.offpay_hash);
			//$('input[name=offpay_hash_batch]').val(result.datas.offpay_hash_batch);

			//提交ajax请求重新计算价格
        	//$.ajax({
        	//	type:'post',
        	//	url:ApiUrl+'/index.php?act=member_buy&op=change_address',
        	//	data:{key:key,area_id:area_id,city_id:city_id,freight_hash:freight_hash},
        	//	dataType:'json',
        	//	success:function(result){
        	//		var data = result.datas;
        	//		var sp_s_total = 0;
        	//		$.each(data.content,function(k,v){
             //           v = pf(v);
				//		$('#store'+k).html(p2f(v));
        	//			var sp_toal = pf($('#st'+k).attr('store_price'));//店铺商品价格
        	//			sp_s_total += v;
        	//			$('#st'+k).html(p2f(sp_toal+v));
        	//		});
            //
				//	var total_price = pf($('input[name=total_price]').val())+sp_s_total;
				//	$('#total_price').html(p2f(total_price));
            //
        	//
            //
        	//		return false;
        	//	}
        	//});
        }else{//保存地址
			if($.sValid()){
				var index = $('select[name=prov]')[0].selectedIndex;
				var aa = $('select[name=prov]')[0].options[index].innerHTML;


				var true_name = $('input[name=true_name]').val();
				var mob_phone = $('input[name=mob_phone]').val();
				var tel_phone = $('input[name=tel_phone]').val();
				var city_id = $('select[name=city]').val();
				var area_id = $('select[name=region]').val();
				var address = $('input[name=vaddress]').val();

				var prov_index = $('select[name=prov]')[0].selectedIndex;
				var city_index = $('select[name=city]')[0].selectedIndex;
				var region_index = $('select[name=region]')[0].selectedIndex;
				var area_info = $('select[name=prov]')[0].options[prov_index].innerHTML+' '+$('select[name=city]')[0].options[city_index].innerHTML+' '+$('select[name=region]')[0].options[region_index].innerHTML;

				//ajax 提交收货地址
				$.ajax({
					type:'post',
					url:WapSiteUrl+'/address/newAddrAdd',
					data:{memberId:userId,trueName:true_name,mobPhone:mob_phone,telPhone:tel_phone,cityId:city_id,areaId:area_id,address:address,areaInfo:area_info},
					dataType:'json',
					success:function(result){
						//保存成功
						if(result.error==null){
							var data = result.datas;
							$('#true_name').html(data.trueName);
							$('#address').html(data.areaInfo+' '+data.address);
							$('#mob_phone').html(data.mobPhone);

							$('input[name=address_id]').val(data.addressId);
							$('input[name=area_id]').val(data.areaId);
							$('input[name=city_id]').val(data.cityId);

							var area_id = data.areaId;
							var city_id = data.cityId;
							var freight_hash = $('input[name=freight_hash]').val();
						}
					}
				});
			}else{
				return false;
			}
        }

        var thisPrarent = $(this).parents(".buys1-address-cnt");
        showDetial(thisPrarent);
    });
    $(".save-invoice").click(function (){//保存发票信息
        var self = this;
        //获取address_id
        var invRadio = $('.inv-radio');
        var inv_id;
        for(var i =0;i<invRadio.length;i++){
            if(invRadio[i].checked){
            	inv_id = invRadio[i].value;
            }
        }

        if(inv_id>0){//选择发票信息
        	var inv_info = $('#inv_'+inv_id).html();
        	$('#inv_content').html(inv_info);//发票信息
        	$("input[name=invoice_id]").val(inv_id);
        }else{//添加发票信息
            var invtRadio = $('input[name=inv_title_select]');
            var inv_title_select;
            for(var i =0;i<invtRadio.length;i++){
                if(invtRadio[i].checked){
                	inv_title_select = invtRadio[i].value;
                }
            }

            var inv_content = $('select[name=inv_content]').val();
            if(inv_title_select == 'company'){
            	var inv_title = $("input[name=inv_title]").val();
            	var data = {memberId:userId,invTitle:inv_title,invContent:inv_content};
            	var html = inv_title+' ';
            }else{
				var inv_title = "个人";
            	var data = {memberId:userId,invTitle:inv_title,invContent:inv_content};
            	var html = '个人  ';
            }
            $.ajax({
            	type:'post',
            	url:WapSiteUrl+'/invoice/add',
            	data:data,
            	dataType:'json',
            	success:function(result){
            		if(result.datas.invId>0){
    					var html1 = '<li>'
										+'<label>'
											+'<input type="radio" name="invoice" class="rdo inv-radio" checked="checked" value="'+result.datas.invId+'"/>'
											+'<span class="mr5 rdo-span" id="inv_'+result.datas.invId+'">'+html+'&nbsp;&nbsp;'+inv_content+'</span>'
										+'</label>'
										+'<a class="del-invoice" href="javascript:void(0);" inv_id="'+result.datas.invId+'">[删除]</a>'
									+'</li>';

    					$('#invoice_add').before(html1);
            			$('#inv_content').html(html+inv_content);//发票信息
            			$('input[name=invoice_id]').val(result.datas.invId);


        				$('.del-invoice').click(function(){
                            var $this = $(this);
        					var inv_id = $(this).attr('inv_id');
        					$.ajax({
        						type:'post',
        						url:WapSiteUrl+'/invoice/delete',
        						data:{invId:inv_id},
        						success:function(result){
        							if(result){
        								$this.parent('li').remove();
        							}
        							return false;
        						}
        					});
        				});
            		}
            	}
            });

        }

        var thisPrarent = $(this).parents(".buys1-invoice-cnt");
        showDetial(thisPrarent);
    });
    $(".no-invoice").click(function (){
        $('#inv_content').html("不需要发票");
        $('input[name=invoice_id]').val('');
        var thisPrarent = $(this).parents(".buys1-invoice-cnt");
        showDetial(thisPrarent);
    });

    //$('#pguse').click(function(){//验证密码
    //	var loginpassword = $("input[name=loginpassword]").val();
    //	if(loginpassword == ''){
    //		$('.password_error_tip').show();
    //		$('.password_error_tip').html('支付密码不能为空');
    //		return false;
    //	}
    //	$.ajax({
    //		type:'post',
    //		url:WapSiteUrl+'/index.php?act=member_buy&op=check_password',
    //		data:{key:key,password:loginpassword},
    //		dataType:'json',
    //		success:function(result){
    //			if(result.datas == 1){
    //				$('input[name=passwd_verify]').val('1');
    //				$('#pd').hide();
    //			}else{
    //				$('#pd').show();
    //				$('.password_error_tip').show();
    //				$('.password_error_tip').html(result.datas.error);
    //			}
    //		}
    //	});
    //});

    //$('#usepdpy,#usercbpay').click(function(){//验证密码切换
    //	if($('#usepdpy').attr('checked') || $('#usercbpay').attr('checked')){
    //		$('#pd').show();
    //	}else{
    //		$('#pd').hide();
    //	}
    //});

	//提交订单step2
    $('#buy_step2').click(function(){
    	var data = {};

    	data.userId = userId;
    	if(ifcart == 1){//购物车订单
    		data.ifcart = ifcart;
    	}
    	data.cartId = cart_id;
		data.orderType=1;
    	var address_id = $('input[name=address_id]').val();
    	data.addressId = address_id;

        //获取支付方式
        var payRadio = $('input[name=buy-type]');
        var pay_name;
        for(var i =0;i<payRadio.length;i++){
            if(payRadio[i].checked){
            	pay_name = payRadio[i].value;
            }
        }
        data.paymentCode = pay_name;
		//获取发票信息
        var invoice_id = $('input[name=invoice_id]').val();
        data.invoiceId = invoice_id;
		//获取总价
		var totalPrice = $('input[name=totalPrice]').val();
		data.totalPrice = totalPrice;


		//alert(data.addressId+","+data.userId+","+data.paymentCode+","+data.invoiceId+","+data.cartId+","+data.totalPrice);
        $.ajax({
        	type:'post',
        	url:WapSiteUrl+'/goods/createOrder',
        	data:data,
        	dataType:'json',
        	success:function(result){

        		//return false;
        		//checklogin(result.login);
        		//if(result.datas.error != ''){
        			//return false;
        		//}

                if (result.info) {
                    $.sDialog({
                        skin:"red",
                        content:result.info,
                        okBtn:false,
                        cancelBtn:false
                    });
                    return false;
                }

        		if(result.orderId != null){
        			location.href = WapSiteUrl+'/wxPay/getAuthorize?type=1&orderId='+result.orderId+'&orderSN='+result.orderSn;
        		}
        		return false;
        	}
        });
    });

	/**
	 * 秒杀提交订单
	 */
	var clicked = false;
	$('#miaosha_btn').click(function(){
		//避免重复提交
		if(!clicked){
			clicked = true;
			var data = {};

			data.userId = userId;

			var address_id = $('input[name=address_id]').val();
			if(address_id==null || address_id==""){
				//alert("请设置地址");
				$.sDialog({
					skin:"red",
					content:"请选择收货地址",
					okBtn:false,
					cancelBtn:false
				});
				return;
			}
			data.addressId = address_id;

			//获取支付方式
			var payRadio = $('input[name=buy-type]');
			var pay_name;
			for(var i =0;i<payRadio.length;i++){
				if(payRadio[i].checked){
					pay_name = payRadio[i].value;
				}
			}
			data.paymentCode = pay_name;
			//获取发票信息
			var invoice_id = $('input[name=invoice_id]').val();
			data.invoiceId = invoice_id;
			//获取总价
			var totalPrice = $('input[name=totalPrice]').val();
			data.totalPrice = totalPrice;
			data.orderType = 2;


			//alert(data.addressId+","+data.userId+","+data.paymentCode+","+data.invoiceId+","+data.totalPrice);
			$.ajax({
				type:'post',
				url:WapSiteUrl+'/goods/createOrder',
				data:data,
				dataType:'json',
				success:function(result){

					if (result.success==0) {
						//alert(result.info);
						if(result.info=="hasOrder"){
							//已经秒杀过的，给出提示以及跳转按钮
							$.sDialog({
								skin: "block",
								content: "您已成功秒杀过该商品，请勿重复秒杀",
								"okBtnText": "查看订单",
								//"cancelBtnText": "立即支付",
								okFn: function () {
									window.location.href = WapSiteUrl+'/order/list?orderState=10';
								}
								//cancelFn: function () {
								//	window.location.href = WapSiteUrl+'/wxPay/getAuthorize?type=1&orderId='+result.orderId+'&orderSN='+result.orderSn;
								//}
							});
						}else{
							$.sDialog({
								skin:"red",
								content:result.info,
								okBtn:false,
								cancelBtn:false
							});
						}
					}else if(result.success==1){
						$.sDialog({
							skin: "block",
							content: "恭喜您，秒杀成功！",
							"okBtnText": "查看订单",
							"cancelBtnText": "立即支付",
							okFn: function () {
								window.location.href = WapSiteUrl+'/order/list?orderState=10';
							},
							cancelFn: function () {
								window.location.href = WapSiteUrl+'/wxPay/getAuthorize?type=1&orderId='+result.orderId+'&orderSN='+result.orderSn;
							}
						});
					}

					//if(result.orderId != null){
					//	location.href = WapSiteUrl+'/wxPay/getAuthorize?type=1&orderId='+result.orderId+'&orderSN='+result.orderSn;
					//}
				}
			});
		}

	});

    function showDetial(parent){
        $(parent).find(".buys1-edit-btn").show();
        $(parent).find(".buys1-hide-list").addClass("hide");
        $(parent).find(".buys1-hide-detail").removeClass("hide");
    }
    function hideDetail(parent){
        $(parent).find(".buys1-edit-btn").hide();
        $(parent).find(".buys1-hide-list").removeClass("hide");
        $(parent).find(".buys1-hide-detail").addClass("hide");
    }
});